package com.jz.community.modulemine.information.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.UserInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.task.GetBindWeChatInfoTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WXUtils;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.information.bean.SpecialCouponBean;
import com.jz.community.basecomm.bean.WeChatInfo;
import com.jz.community.modulemine.information.task.GetBindUserInfoTask;
import com.jz.community.basecomm.task.GetWeChatOpenIdTask;
import com.jz.community.modulemine.information.view.SpecialCouponDialog;
import com.jz.community.modulemine.information.task.SpecialCouponTask;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import butterknife.BindView;

/**
 * Created by Admin on 2018/3/30 0030.
 */

public class UserInfoActivity extends BaseMvpActivity {

    @BindView(R2.id.title_back)
    ImageButton titleBack;
    @BindView(R2.id.im_user_name)
    TextView im_user_name;
    @BindView(R2.id.im_wechat)
    TextView im_wechat;
    @BindView(R2.id.im_phone)
    TextView im_phone;
    @BindView(R2.id.bind_wechat_layout)
    LinearLayout bindWechatLayout;
    @BindView(R2.id.wechat_layout)
    LinearLayout wechatLayout;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.title_name)
    TextView titleName;

    public static final int MODIFY_NAME = 24;
    public static final int BINDING_PHONE = 205;
    private LoginBaseInfo loginBaseInfo;


    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_user_info;
    }


    @Override
    protected void initDatas() {
        registerWeChatApp();
        setImmersionBar(titleToolbar);
        titleName.setText("我的信息");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstants.WEIXIN_LOGIN_INTENT_ACTION);
        registerReceiver(weChatCodeReceiver, intentFilter);
        loginBaseInfo = BaseSpUtils.getInstance().getUserBaseInfo(this);
        getIsBindUser();
        setUserInfo(loginBaseInfo);
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void addListener() {

        titleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        im_user_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserInfoActivity.this, UpdateUserActivity.class);
                startActivityForResult(intent, MODIFY_NAME);
            }
        });
        im_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindingWechat();
            }
        });
        im_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Preconditions.isNullOrEmpty(loginBaseInfo.getMobi())) {
                    startActivityForResult(new Intent(UserInfoActivity.this, BindingPhoneActivity.class), BINDING_PHONE);
                }
            }
        });
    }

    private void bindingWechat() {
        if (WXUtils.getInstance().isWxInstalledAndSurported(this)) {
            if (Preconditions.isNullOrEmpty(loginBaseInfo.getNickname())) {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = AppConstants.WX_LOGIN_SCOPE;
                req.state = AppConstants.WEIXIN_LOGIN_INTENT_ACTION;
                api.sendReq(req);
            }
        } else {
            WpToast.l(this, "请先安装微信客户端");
        }
    }

    private void setUserInfo(LoginBaseInfo userInfo) {
        if (!Preconditions.isNullOrEmpty(userInfo)) {
            im_user_name.setText(userInfo.getName());
            if (!Preconditions.isNullOrEmpty(BaseSpUtils.getInstance().getNickname(this))) {
                im_wechat.setEnabled(false);
                if (!Preconditions.isNullOrEmpty(BaseSpUtils.getInstance().getNickname(this))) {
                    im_wechat.setText(BaseSpUtils.getInstance().getNickname(this));
                } else {
                    im_wechat.setText("已绑定");
                }
                im_wechat.setCompoundDrawables(null, null, null, null);
                im_wechat.setTextColor(getResources().getColor(R.color.text_light));
            } else {
                SHelper.vis(bindWechatLayout, wechatLayout);
                im_wechat.setText("未绑定");
                im_wechat.setTextColor(getResources().getColor(R.color.dodge_blue));
            }

            if (Preconditions.isNullOrEmpty(userInfo.getMobi())) {
                im_phone.setText("绑定手机领优惠券");
                im_phone.setTextColor(getResources().getColor(R.color.dodge_blue));
            } else {
                im_phone.setText(userInfo.getMobi());
                im_phone.setCompoundDrawables(null, null, null, null);
                im_phone.setTextColor(getResources().getColor(R.color.text_light));
            }
        }
    }

    //第三方微信登录通知广播
    BroadcastReceiver weChatCodeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String code = intent.getStringExtra("code");
            getWenXinOpenId(code);
        }
    };

    private void getIsBindUser() {
        new GetBindUserInfoTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                UserInfo userInfo = (UserInfo) o;
                if (!Preconditions.isNullOrEmpty(userInfo)) {
                    im_wechat.setEnabled(false);
                    if (!Preconditions.isNullOrEmpty(BaseSpUtils.getInstance().getNickname(UserInfoActivity.this))) {
                        im_wechat.setText(BaseSpUtils.getInstance().getNickname(UserInfoActivity.this));
                    } else {
                        im_wechat.setText("已绑定");
                    }
                    im_wechat.setCompoundDrawables(null, null, null, null);
                    im_wechat.setTextColor(getResources().getColor(R.color.text_light));
                }
            }
        }).execute();
    }

    private void getWenXinOpenId(String code) {
        new GetWeChatOpenIdTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                WeChatInfo weChatInfo = (WeChatInfo) o;
                if (!Preconditions.isNullOrEmpty(weChatInfo)) {
                    bindWeChat(weChatInfo.getInfo().getOpenId(), weChatInfo.getInfo().getUnionId(), "1");
                }
            }
        }).execute(code);
    }

    private void bindWeChat(String openId, String unionId, String type) {
        //绑定成功后获取优惠券
        if ("2".equals(type)) {
            getCoupon();
        }
        new GetBindWeChatInfoTask(this, o -> {
            BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
            if (Preconditions.isNullOrEmpty(baseResponseInfo)) {
                return;
            }
            if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
                im_wechat.setText(BaseSpUtils.getInstance().getNickname(UserInfoActivity.this));
                im_wechat.setCompoundDrawables(null, null, null, null);
                im_wechat.setTextColor(getResources().getColor(R.color.text_light));
            } else {
                WpToast.l(UserInfoActivity.this, baseResponseInfo.getMessage());
            }
        }).execute(openId, unionId, type);
    }


    private void getCoupon() {
        new SpecialCouponTask(this, o -> {
            SpecialCouponBean specialCouponBean = (SpecialCouponBean) o;
            if (Preconditions.isNullOrEmpty(specialCouponBean)) {
                return;
            }
            SpecialCouponDialog dialog = new SpecialCouponDialog(UserInfoActivity.this);
            dialog.setData(specialCouponBean);
            dialog.show();
        }).execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (BINDING_PHONE == requestCode && resultCode == RESULT_OK) {
            String phone = data.getStringExtra("phone");
            im_phone.setText(phone);
            bindWeChat(phone, "", "2");
        } else if (requestCode == MODIFY_NAME && resultCode == RESULT_OK) {
            String nickName = data.getStringExtra("nickName");
            im_user_name.setText(nickName);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (weChatCodeReceiver != null) {
            unregisterReceiver(weChatCodeReceiver);
        }
    }
}
